﻿using System;

using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Drawing;
using System.Text;
using System.Reflection;
using System.Windows.Forms;
using Microsoft.Win32;
using Microsoft.WindowsMobile.PocketOutlook;
using Microsoft.WindowsMobile.Forms;

namespace SMSTasker
{
    public partial class fmMain : System.Windows.Forms.Form
    {
        public fmMain()
        {
            InitializeComponent();
            MyInitializeComponents();
            Localize();
        }

        private void MyInitializeComponents()
        {
            this.KeyPreview = true;

            label1.Visible = false;
        }

        private void AddContactItem(String ContactName, String ContactPhone)
        {
            this.SuspendLayout();
            ContactItem item = new ContactItem(ContactName, ContactPhone);
            Point scales = new Point(((int)this.CurrentAutoScaleDimensions.Width) / 96, ((int)this.CurrentAutoScaleDimensions.Height) / 96);
            item.Scales = scales;
            Point newPos;
            Size newSize;

            newPos = new System.Drawing.Point(5 * scales.Y, 25 * scales.Y + GetContactItemsCount() * (5 * scales.Y + item.Height));
            newSize = new System.Drawing.Size(213 * scales.X, 36 * scales.Y);

            item.Location = newPos;
            item.Size = newSize;

            item.Click += new System.EventHandler(ContactItem_Click);

            this.Controls.Add(item);
            this.ResumeLayout(false);
        }

        // Paints the background of the form with a GradientFill pattern.
        protected override void OnPaintBackground(PaintEventArgs e)
        {
            // On Windows Mobile Pocket PC 2003, the call to GradientFill
            // fails with GetLastError() returning 87 (ERROR_INVALID_PARAMETER)
            // when e.Graphics is used.
            // Instead, fill into a bitmap and then draw that onto e.Graphics.
            Bitmap bm = new Bitmap(Width, Height);
            Graphics gr = System.Drawing.Graphics.FromImage(bm);

            GradientFill.Fill(
                gr,
                this.ClientRectangle,
                Color.White, Color.LightBlue,
                GradientFill.FillDirection.LeftToRight);
            e.Graphics.DrawImage(bm, 0, 0);
            ControlBitmapExtensions.DrawLabel(label1, e.Graphics);
            gr.Dispose();
            bm.Dispose();
        }


        private int GetContactItemsCount()
        {
            int count = 0;
            foreach (Object obj in this.Controls)
            {
                if (obj is ContactItem)
                {
                    count++;
                }
            }
            return count;
        }

        private void UnSelectAll()
        {
            foreach (Object obj in this.Controls)
            {
                if (obj is ContactItem)
                {
                    ContactItem item = (ContactItem)obj;
                    item.BackColor = item.UnSelectedColor;
                    item.lbName.ForeColor = item.UnSelectedFontColor;
                    item.lbPhone.ForeColor = item.UnSelectedFontColor;
                }
            }
        }

        private void SelectItem(ContactItem item)
        {
            item.BackColor = item.SelectedColor;
            item.lbName.ForeColor = item.SelectedFontColor;
            item.lbPhone.ForeColor = item.SelectedFontColor;
        }

        private void UnSelectItem(ContactItem item)
        {
            item.BackColor = item.UnSelectedColor;
            item.lbName.ForeColor = item.UnSelectedFontColor;
            item.lbPhone.ForeColor = item.UnSelectedFontColor;
        }

        private void ContactItem_Click(object sender, EventArgs e)
        {
            this.SuspendLayout();
            UnSelectAll();
            Point scales = new Point(((int)this.CurrentAutoScaleDimensions.Width) / 96, ((int)this.CurrentAutoScaleDimensions.Height) / 96);
            SelectItem((ContactItem)sender);
            this.ResumeLayout(false);
            fmQuestion qu = new fmQuestion();
            qu.ContactName = ((ContactItem)sender).ContactName;
            qu.ShowDialog();
            if (qu.DialogResult == DialogResult.OK)
            {
                this.SuspendLayout();
                List<ContactItem> ContactItems = new List<ContactItem>();
                foreach (Object obj in this.Controls)
                {
                    if (!(obj is ContactItem))
                    {
                        continue;
                    }
                    ContactItem item = (ContactItem)obj;
                    if (item.BackColor == item.SelectedColor)
                    {
                        this.Controls.Remove(item);
                    }
                    else
                    {
                        ContactItems.Add(item);
                    }
                }
                for (int i = 0; i < ContactItems.Count; i++)
                {
                    ContactItems[i].Left = 5 * scales.X;
                    ContactItems[i].Top = 25 * scales.Y + i * (5 * scales.Y + ContactItems[i].Height);
                }
                this.ResumeLayout(false);
                SaveData();
            }
        }

        private void menuItem2_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void menuItem3_Click(object sender, EventArgs e)
        {
            About aForm = new About();
            aForm.ShowDialog();
        }

        private void menuItem1_Click(object sender, EventArgs e)
        {
            ChooseContactDialog dial = new ChooseContactDialog();
            dial.ChooseContactOnly = true;
            if (dial.ShowDialog() == DialogResult.OK)
            {
                dial.ChoosePropertyOnly = true;
                dial.RequiredProperties = new ContactProperty[] { ContactProperty.AllPhone };
                dial.ShowDialog();
                if (dial.SelectedPropertyValue != null)
                {
                    Contact user = dial.SelectedContact;
                    bool phoneExist = false;
                    foreach (Object obj in this.Controls)
                    {
                        if ((obj is ContactItem) && (((ContactItem)obj).ContactPhone.CompareTo(dial.SelectedPropertyValue) == 0))
                        {
                            phoneExist = true;
                        }
                    }
                    if (!phoneExist)
                    {
                        AddContactItem(user.FileAs, dial.SelectedPropertyValue);
                        SaveData();
                    }
                }
            }
        }

        private void SaveData()
        {
            RegistryKey hKey = Registry.CurrentUser.OpenSubKey("\\Software\\Introkun\\SMSTasker", true);
            if (hKey == null)
            {
                hKey = Registry.CurrentUser.CreateSubKey("\\Software\\Introkun\\SMSTasker");
            }
            String result = "";
            foreach (Object obj in this.Controls)
            {
                if (obj is ContactItem)
                {
                    result += ((ContactItem)obj).ContactPhone + ";";
                }
            }
            hKey.SetValue("Phones", result, RegistryValueKind.String);
        }

        private void fmMain_Load(object sender, EventArgs e)
        {
            using(RegistryKey hKey  = Registry.CurrentUser.OpenSubKey("\\Software\\Introkun\\SMSTasker", true))
            {
                if (hKey == null)
                {
                    return;
                }
                String phonesString = (String)hKey.GetValue("Phones");
                if (phonesString == null)
                {
                    return;
                }
                List<String> phones = new List<String>(phonesString.Split(';'));
                if (phones[phones.Capacity - 1] == "")
                {
                    phones.RemoveAt(phones.Capacity - 1);
                }
                OutlookSession mySession = new OutlookSession();
                foreach (String phone in phones)
                {
                    foreach (Contact cont in mySession.Contacts.Items)
                    {
                        if (cont.MobileTelephoneNumber.CompareTo(phone) == 0)
                        {
                            AddContactItem(cont.FileAs, cont.MobileTelephoneNumber);
                            break;
                        }
                        if (cont.BusinessTelephoneNumber.CompareTo(phone) == 0)
                        {
                            AddContactItem(cont.FileAs, cont.BusinessTelephoneNumber);
                            break;
                        }
                        if (cont.CarTelephoneNumber.CompareTo(phone) == 0)
                        {
                            AddContactItem(cont.FileAs, cont.CarTelephoneNumber);
                            break;
                        }
                        if (cont.CompanyTelephoneNumber.CompareTo(phone) == 0)
                        {
                            AddContactItem(cont.FileAs, cont.CompanyTelephoneNumber);
                            break;
                        }
                        if (cont.RadioTelephoneNumber.CompareTo(phone) == 0)
                        {
                            AddContactItem(cont.FileAs, cont.RadioTelephoneNumber);
                            break;
                        }
                    }
                }

                // записываем файл языка с которым мы работаем для smshandler
                String localesPath = Path.GetDirectoryName(Localizer.GetLocalizationFilePath());
                hKey.SetValue("LocalesPath", localesPath);
            }
        }

        private void Localize()
        {
            label1.Text = Localizer.Instance.GetString("fmMain.Label");
            menuItem4.Text = Localizer.Instance.GetString("fmMain.Menu");
            menuItem1.Text = Localizer.Instance.GetString("fmMain.Add");
            menuItem3.Text = Localizer.Instance.GetString("fmMain.About");
            menuItem2.Text = Localizer.Instance.GetString("fmMain.Quit");
            menuItem6.Text = Localizer.Instance.GetString("fmMain.Send");
            menuItem7.Text = Localizer.Instance.GetString("fmMain.Settings");
        }

        private void menuItem6_Click(object sender, EventArgs e)
        {
            fmSender taskSender = new fmSender();
            taskSender.ShowDialog();
            //TODO проверить результат
        }

        private void menuItem7_Click(object sender, EventArgs e)
        {
            RegistryKey hKey = Registry.CurrentUser.OpenSubKey("\\Software\\Introkun\\SMSTasker", true);
            fmSettings appSettings = new fmSettings();
            if (hKey != null)
            {
                if (hKey.GetValue("AddToContactCategory") != null)
                {
                    appSettings.cbAddContactInfo.Checked = hKey.GetValue("AddToContactCategory").ToString().ToLower() == "true";
                }
                if (hKey.GetValue("PlaySound") != null)
                {
                    appSettings.cbPlaySound.Checked = hKey.GetValue("PlaySound").ToString().ToLower() == "true";
                }
                if (hKey.GetValue("ShowBaloon") != null)
                {
                    appSettings.cbShowBaloon.Checked = hKey.GetValue("ShowBaloon").ToString().ToLower() == "true";
                }
                if (hKey.GetValue("ReceiveFromAll") != null)
                {
                    appSettings.cbReceiveFromAll.Checked = hKey.GetValue("ReceiveFromAll").ToString().ToLower() == "true";
                }
            }
            appSettings.ShowDialog();

            if (appSettings.DialogResult == DialogResult.OK)
            {
                if (hKey == null)
                {
                    hKey = Registry.CurrentUser.CreateSubKey("\\Software\\Introkun\\SMSTasker");
                }
                hKey.SetValue("AddToContactCategory", appSettings.cbAddContactInfo.Checked.ToString());
                hKey.SetValue("PlaySound", appSettings.cbPlaySound.Checked.ToString());
                hKey.SetValue("ShowBaloon", appSettings.cbShowBaloon.Checked.ToString());
                hKey.SetValue("ReceiveFromAll", appSettings.cbReceiveFromAll.Checked.ToString());
            }
        }

//         protected override void OnKeyDown(KeyEventArgs e)
//         {
//             List<ContactItem> list = new List<ContactItem>();
//             bool isSelected = false;
//             foreach (Object obj in this.Controls)
//             {
//                 if (obj is ContactItem)
//                 {
//                     if (((ContactItem)obj).BackColor == SelectedColor)
//                     {
//                         isSelected = true;
//                     }
//                     list.Add((ContactItem)obj);
//                 }
//             }
//             switch (e.KeyCode)
//             {
//                 case Keys.Right:
//                 case Keys.Down:
//                     if (!isSelected)
//                     {
//                         SelectItem(list[0]);
//                         break;
//                     }
//                     for (int i = 0; i < list.Count - 1; i++)
//                     {
//                         if (list[i].BackColor == SelectedColor)
//                         {
//                             UnSelectItem(list[i]);
//                             SelectItem(list[i + 1]);
//                             break;
//                         }
//                     }
//                     break;
//                 case Keys.Left:
//                 case Keys.Up:
//                     if (!isSelected)
//                     {
//                         SelectItem(list[list.Count-1]);
//                         break;
//                     }
//                     for (int i = 1; i < list.Count; i++)
//                     {
//                         if (list[i].BackColor == SelectedColor)
//                         {
//                             UnSelectItem(list[i]);
//                             SelectItem(list[i - 1]);
//                             break;
//                         }
//                     }
//                     break;
//             }
//         }
    }
}